import {AxdrSequenceOf} from "../asn1.axdr/AxdrSequenceOf";
import {GetRecord} from "./GetRecord";
import {Buffer} from "buffer";
import {PIID} from "./PIID";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";


export class SubSeqOfGetRecords extends AxdrSequenceOf<GetRecord>{

    createListElement(): GetRecord {
        return new GetRecord();
    }

    constructor() {
        super();
    }

}

export class GetRequestRecordList implements AxdrType{

    dataCode : Buffer | null = null;
    piid : PIID | null = null;
    getRecords : SubSeqOfGetRecords | null = null;

    constructor() {

    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(piid : PIID, getRecords : SubSeqOfGetRecords){
        this.piid = piid;
        this.getRecords = getRecords;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.piid = new PIID();
        this.piid.setNumBit(8);
        codeLength += this.piid.decode(input);

        this.getRecords = new SubSeqOfGetRecords();
        codeLength += this.getRecords.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {

        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.getRecords != null && this.piid != null){
                codeLength = 0;
                codeLength += this.getRecords.encode(output);
                codeLength += this.piid.encode(output);
            }else{
                throw new Error("getRecords or piid is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.piid != null && this.getRecords != null) {
            return "sequence: {" + "piid: " + this.piid + ", getRecords: " + this.getRecords + "}";
        } else {
            return "piid || getRecords is null";
        }
    }

}
